package com.wffz.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.wffz.comm.utils.CommUtils;
import com.wffz.comm.utils.DateUtils;
import com.wffz.dto.AwardDTO;
import com.wffz.mapper.PatchMapper;
import com.wffz.po.*;
import com.wffz.service.BetService;
import com.wffz.service.PatchService;
import com.wffz.service.WffzConfigService;
import com.wffz.vo.PrizesVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.core.parameters.P;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Locale;
import java.util.Random;

/**
 * @author sunlei
 * @className PatchServiceImpl
 * @Description
 * @date 2023-02-12 11:19
 **/
@Service
@Slf4j
public class PatchServiceImpl implements PatchService {

    @Resource
    private PatchMapper patchMapper;


    @Resource
    private WffzConfigService configService;


    @Resource
    private BetService betService;

    @Override
    public boolean insertPatch(Patch patch) {
        return patchMapper.insert(patch) > 0;
    }

    @Override
    public boolean updatePatch(Patch patch) {
        int res = patchMapper.updateById(patch);
        return res > 0;
    }

    @Override
    public boolean saveDayPatch(String dayTime, String type) {
        // 一天86400秒
        long dayMM = 86400;
        // 一天盘口秒数
        long patchMM = 0;

        switch (type) {
            case "0":
                patchMM = 60;
                break;
            case "1":
                patchMM = 120;
                break;
            case "2":
                patchMM = 180;
                break;
            case "3":
                patchMM = 30;
                break;
            default:
                patchMM = 30;
        }

        log.info("patchMM : " + patchMM);

        int res = 0;
        Patch patch = null;
        for (int i = 0; i < dayMM / patchMM; i++) {
            patch = new Patch();
            String patchNum = dayTime + getFourStr(i);
            patch.setPatchType(type);
            patch.setPatchNum(patchNum);
            patch.setCreateTime(new Date());
            if (i == 0) {
                patch.setStatus("1");
            } else {
                patch.setStatus("0");
            }
            patch.setCountDown((int) patchMM);
            patch.setCreateDay(dayTime);
            res = patchMapper.insert(patch);
        }

        return res > 0;
    }

    @Override
    public Integer getPatchCountByDay(String dayTime, String type) {
        QueryWrapper<Patch> wrapper = new QueryWrapper<>();
        wrapper.eq("create_day", dayTime);
        wrapper.eq("patch_type", type);
        return patchMapper.selectCount(wrapper);
    }

    @Override
    public Patch getCurrentPeriod(String type) {
        String nowDay = DateUtils.dateTimeNow("yyyyMMdd");
        Patch patch = null;
        QueryWrapper<Patch> wrapper = new QueryWrapper<>();
        wrapper.eq("status", "1");
        wrapper.eq("create_day", nowDay);
        wrapper.eq("patch_type", type);
        wrapper.orderByDesc("create_time").last(" limit 1");
        List<Patch> patches = patchMapper.selectList(wrapper);
        if (patches != null && patches.size() > 0) {
            patch = patches.get(0);
        }
        return patch;
    }

    @Override
    public Patch getPatchByNum(String patchNum, String type) {
        Patch patch = null;
        QueryWrapper<Patch> wrapper = new QueryWrapper<>();
        wrapper.eq("patch_num", patchNum);
        wrapper.eq("patch_type", type);
        wrapper.orderByDesc("create_time").last(" limit 1");
        List<Patch> patches = patchMapper.selectList(wrapper);
        if (patches != null && patches.size() > 0) {
            patch = patches.get(0);
        }
        return patch;
    }


    @Override
    public AwardDTO awardColor(String patchNum, String patchType) {
        AwardDTO awardDTO = null;
        //
        String color = "0";
        // 获取开奖模式 可以放到redis缓存
        String key = "win_mode";
        WffzConfig config = configService.getConfigByKey(key);
        String value = config.getConfigValue();
        //
        Random random = new Random();
        // 随机开奖
        if (value.equals("0")) {
            //随机一个0-9的数字
            int number = random.nextInt(10);
            if (number == 1 || number == 3 || number == 7 || number == 9) {
                color = "0";
            } else if (number == 2 || number == 4 || number == 6 || number == 8) {
                color = "2";
            } else {
                color = "1";
            }
            awardDTO = new AwardDTO();
            awardDTO.setColor(color);
            awardDTO.setNumber(number);
        } else if (value.equals("1")) {
            // 获取少的开奖  后期考虑用redis计数器
            List<Bet> list = betService.getBetGroupColor(patchNum, patchType);
            if (CommUtils.isNotEmptyList(list)) {
                awardDTO = new AwardDTO();
                color = list.get(0).getBetColor();
                int kjNumber = 0;
                int numberGreenArr[] = {1, 3, 7, 9};
                int numberRedArr[] = {2, 4, 6, 8};
                int numberVArr[] = {0, 5};
                if (color.equals("0")) {
                    // 绿色
                    int n = random.nextInt(3);
                    kjNumber = numberGreenArr[n];
                } else if (color.equals("2")) {
                    // 红色
                    int n = random.nextInt(3);
                    kjNumber = numberRedArr[n];
                } else {
                    int n = random.nextInt(1);
                    kjNumber = numberVArr[n];
                }
                awardDTO.setColor(color);
                awardDTO.setNumber(kjNumber);
            }
        }
        if (awardDTO == null) {
            awardDTO = new AwardDTO();
            awardDTO.setNumber(1);
            awardDTO.setColor("0");
        }
        return awardDTO;
    }

    /**
     * @Description: [开奖 ，如果中奖  给上级  上上级  上上上级别返佣]
     * @Title: PrizesResult 开奖
     * @Author: SUNLEI
     * @Date: 2023-03-21
     * @Param: bet
     * @Return: java.lang.Float
     * @Throws:
     */
    @Override
    public PrizesVO PrizesResult(Bet bet) {
        PrizesVO vo = new PrizesVO();
        String key = "brokerage";
        WffzConfig config = configService.getConfigByKey(key);
        float brokerage = Float.parseFloat(config.getConfigValue());
        float result = 0;
        String patchType = bet.getPatchType();
        // 期码
        String patchNum = bet.getPeriodCode();
        // 获取下单类型
        String betType = bet.getBetType();
        // 获取下单号码
        Integer betNumber = bet.getBetNumber();
        // 下注金额
        float cost = bet.getBetCost();
        // 获取当期数据
        Patch p = this.getPatchByNum(patchNum, patchType);
        // 开奖号码
        int prizesNum = p.getPrizesNum();
        // 开奖颜色
        String prizesColor = p.getPrizesColor();
        if (betType.equals("0")) {
            // 中奖了
            if (bet.getBetColor().equals(prizesColor)) {
                float earningMultiple = 2;
                switch (bet.getBetColor()) {
                    case "0":
                        log.info("green ");
                        earningMultiple = 2;
                        break;
                    case "1":
                        log.info("violet");
                        earningMultiple = 4.5F;
                        break;
                    case "2":
                        earningMultiple = 2;
                        log.info("red");
                        break;
                }
                result = cost * earningMultiple * (1f - brokerage);
            }
        } else {
            if (betNumber == prizesNum) {
                result = cost * 9 * (1f - brokerage);
            }
        }
        bet.setWinAmount(result);
        ClientUser c = betService.update(bet);
        vo.setUser(c);
        vo.setPrizesResult(result);
        return vo;
    }

    @Override
    public List<Patch> queryAwardPatch(String type) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
        String day = sdf.format(new Date());
        QueryWrapper<Patch> wrapper = new QueryWrapper<>();
        wrapper.eq("patch_type", type);
        wrapper.eq("status", "2");
        wrapper.eq("create_day", day);
        wrapper.orderByDesc("patch_num");
        wrapper.last("limit 0 , 20");
        List<Patch> l = patchMapper.selectList(wrapper);
        return l;
    }


    @Override
    public List<Patch> queryAwardPatchAll(String type) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
        String day = sdf.format(new Date());
        QueryWrapper<Patch> wrapper = new QueryWrapper<>();
        wrapper.eq("patch_type", type);
        wrapper.eq("status", "2");
        wrapper.eq("create_day", day);
        wrapper.orderByDesc("patch_num");
        List<Patch> l = patchMapper.selectList(wrapper);
        return l;
    }

    public String getFourStr(int i) {
        String str = "";
        if (i < 10) {
            str = "000";
        } else if (i >= 10 && i < 100) {
            str = "00";
        } else if (i >= 100 && i < 1000) {
            str = "0";
        }
        return str + i;
    }
}
